package com.fjec.common.config;

import com.fjec.common.filter.GlobalExceptionFilter;
import org.apache.shiro.spring.web.ShiroFilterFactoryBean;
import org.springframework.boot.web.servlet.FilterRegistrationBean;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

import javax.servlet.DispatcherType;
import javax.servlet.Filter;

@Configuration
public class CommonFilterConfig {

    /**
     * 处理字符集
     */
//    @Bean
//    public FilterRegistrationBean charsetFilter() {
//        FilterRegistrationBean registration = new FilterRegistrationBean();
//        CharacterEncodingFilter filter = new CharacterEncodingFilter();
//        filter.setEncoding("UTF-8");
//        filter.setForceEncoding(true);
//        registration.setFilter(filter);
//        registration.setName("characterEncodingFilter");
//        registration.addUrlPatterns("/*");
//        registration.setOrder(1);
//        return registration;
//    }

    /**
     * 防止xss攻击
     *
     * @return
     */
//    @Bean
//    public FilterRegistrationBean xssFilter() {
//        FilterRegistrationBean registration = new FilterRegistrationBean();
//        registration.setFilter(new XssFilter());
//        registration.setName("xssFilter");
//        registration.setOrder(4);
//        registration.addUrlPatterns("/*");
//        registration.setDispatcherTypes(DispatcherType.REQUEST);
//        return registration;
//    }

    /**
     * 全局异常处理
     */
    @Bean
    public FilterRegistrationBean globalExceptionFilter() {
        FilterRegistrationBean registration = new FilterRegistrationBean();
        registration.setFilter(new GlobalExceptionFilter());
        registration.setName("globalExceptionFilter");
        registration.setOrder(5);
        registration.addUrlPatterns("/*");
        registration.setDispatcherTypes(DispatcherType.REQUEST, DispatcherType.FORWARD,
                DispatcherType.INCLUDE, DispatcherType.ERROR);
        return registration;
    }

    /**
     * Shiro拦截器
     */
    @Bean
    public FilterRegistrationBean springShiroFilter(ShiroFilterFactoryBean shiroFilterFactoryBean) throws Exception {
        FilterRegistrationBean registration = new FilterRegistrationBean();
        registration.setFilter((Filter) shiroFilterFactoryBean.getObject());
        registration.setName("springShiroFilter");
        registration.setOrder(6);
        registration.addUrlPatterns("/*", "/shiro/*");
        registration.setDispatcherTypes(DispatcherType.REQUEST, DispatcherType.FORWARD,
                DispatcherType.INCLUDE, DispatcherType.ERROR);
        return registration;
    }
}
